package model

import (
	"log"
	db "mwwow_service_go/database"
)

type Type struct {
	Id       int    `json:"id",form:"id"`
	TypeName string `json:"typeName",form:"typeName"`
}

// 增加类型
func (t *Type) AddType() (id int64, err error) {
	rs, err := db.SqlDB.Exec("INSERT INTO type(typeName) VALUES(?)", t.TypeName)
	if err != nil {
		return
	}
	id, err = rs.LastInsertId()
	if err != nil {
		return
	}
	return
}

// 删除类型
func (t *Type) DeleteType(id string) (isSuccess bool, err error) {
	rs, err := db.SqlDB.Exec("DELETE FROM type WHERE Id=?", id)
	if err != nil {
		return
	}
	if num, _ := rs.RowsAffected(); num == 0 {
		return
	}
	isSuccess = true
	return
}

// 修改类型
func (t *Type) UpdateType(id string) (isSuccess bool, err error) {
	rs, err := db.SqlDB.Exec("UPDATE type SET typename=? WHERE Id=? ", t.TypeName, id)
	if err != nil {
		return
	}
	if num, _ := rs.RowsAffected(); num == 0 {
		return
	}
	isSuccess = true
	return
}

// 获取类型
func (t *Type) GetType() (types []Type, err error) {
	types = make([]Type, 0)
	rows, err := db.SqlDB.Query("SELECT * FROM type")
	if err != nil {
		log.Fatalln(err)
	}
	defer rows.Close()
	for rows.Next() {
		var tt Type
		rows.Scan(&tt.Id, &tt.TypeName)
		types = append(types, tt)
	}
	if err = rows.Err(); err != nil {
		return
	}
	return
}
